package com.example.lpactivity.fragment.viewpage;

import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import com.example.lpactivity.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ViewPageActivity extends AppCompatActivity {

    private String localPath="file://"+ Environment.getExternalStorageDirectory()+"/track/";
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_page);
        initViews();
    }

    private void initViews() {
        viewPager=findViewById(R.id.viewPager);
        List<Fragment> list=new ArrayList<>();
        FragmentFactory fragmentFactory=new FragmentFactory();

        list.add(fragmentFactory.getFramgnet(localPath+"index.html","Fragment_0"));
        list.add(fragmentFactory.getFramgnet(localPath+"culture.html","Fragment_1"));
        list.add(fragmentFactory.getFramgnet(localPath+"education.html","Fragment_2"));
        list.add(fragmentFactory.getFramgnet(localPath+"future.html","Fragment_3"));
        FragmentAdapter   adapter = new FragmentAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(5);
        setViewPagerScroller();

    }

    private void setViewPagerScroller() {

        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            Field interpolator = ViewPager.class.getDeclaredField("sInterpolator");
            interpolator.setAccessible(true);

            Scroller scroller = new Scroller(this, (Interpolator) interpolator.get(null)) {
                @Override
                public void startScroll(int startX, int startY, int dx, int dy, int duration) {
                    super.startScroll(startX, startY, dx, dy, duration * 7);    // 这里是关键，将duration变长或变短
                }
            };
            scrollerField.set(viewPager, scroller);
        } catch (NoSuchFieldException e) {
            // Do nothing.
        } catch (IllegalAccessException e) {
            // Do nothing.
        }
    }
}
